# -*- coding:utf-8 -*-
import backtrader as bt
#####################
import akshare as ak

import pandas as pd
import datetime
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
#  定义一个名为 Platform 的自定义指标类，继承自 backtrader 的 Indicator 类。
class Platform(bt.Indicator):
    lines = ("上轨","下轨") # 声明该指标有两条线，分别是“上轨”和“下轨”。

    def __init__(self):
        # 是设置策略或指标的最小周期。最小周期是指策略或指标在开始计算之前需要的最少数据点数。
        self.addminperiod(6)   #5天的平台, 表示策略或指标需要至少6个数据点才能开始计算。

    def next(self):
        self.上轨[0]= max(self.data.high.get(ago = -1,size =5))
        self.下轨[0] = min(self.data.low.get(ago=-1, size=5))

class AceStrategy(bt.Strategy):

    def __init__(self):
        self.上下轨 = Platform(self.data)
        self.上下轨.plotinfo.plotmaster = self.data  #类似通达信的 是否在主图显示

    def next(self):
            return

if __name__ == '__main__':

    # 获取平安银行（000001）的日K线数据
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol="000001", period="daily", 
                                            start_date="20200101", end_date='20200315', adjust="qfq")

    # 获取股票后复权数据
    df = ak.stock_zh_a_hist(symbol="000001", period="daily", 
                            start_date="20200101", end_date='20200315', adjust="qfq")
    # 处理字段命名
    df = df[['日期','开盘', '收盘', '最高','最低', '成交量',]]
    df.columns = ['date', 'open', 'close', 'high', 'low', 'volume']
    # 将date设为索引
    df.index = pd.to_datetime(df['date'])
    
    
    
    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(1000000.00)  # 设置初始资金金额
    初始资金 = cerebro.broker.getvalue()
    print(f'初始资金:{初始资金}')
    #datapath = ('000001.csv')
    #dataframe = pd.read_csv(datapath, index_col=0, parse_dates=True)
    data = bt.feeds.PandasData(dataname=df,
                        fromdate=datetime.datetime(2020, 1, 1),
                        todate=datetime.datetime(2022,1,28)
        )
    cerebro.adddata(data)
    cerebro.addstrategy(AceStrategy)
    cerebro.run()
    期末资金 =  cerebro.broker.getvalue()
    print(f'期末资金:{期末资金}')
    
    cerebro.plot(style='candlestick',figsize=(12, 8))